/*
 * @Description: 转档案按钮
 * @Author: Zzt
 * @Date: 2023-01-13 11:17:06
 * @LastEditTime: 2023-01-16 16:28:54
 */
import { fetchArchivesByRule, transferArchive } from '@/api/archives/archives';
import { fetchATListByFondId } from '@/api/archivesType';
import { fetchFondsListByUnitId } from '@/api/fonds';
import { IArchiveType } from '@/interfaces/archiveType';
import { IFond } from '@/interfaces/fond';
import { appState } from '@/store/mobx';
import { selectItemByKey } from '@/utils/list';
import { selectMappingList } from '@/api/mapping';
import { Button, Form, Modal, Radio, Select, Space } from 'antd';
import { observer } from 'mobx-react-lite';
import { memo, useEffect, useMemo, useState } from 'react';

const TransferFileModal = (props: any) => {
  const { visible, baseInfo, selectItems, onClose } = props;
  const [form] = Form.useForm();
  // 全宗列表
  const [fondsList, setFondsList] = useState([]);
  // 档案类型列表
  const [ATList, setATList] = useState<IArchiveType[]>([]);
  // // 选中的全宗
  // const [selectFondId, setSelectFondId] = useState(0);
  // // 选中的档案类型id
  // const [selectATId, setSelectATId] = useState(0);
  // const [fondItem, setFondItem] = useState();
  /* 映射模板列表 */
  const [mappingList, setMappingList] = useState([]);
  /* 案卷列表 */
  const [fileList, setFileList] = useState([]);
  const [atItem, setAtItem] = useState<any>({});
  useEffect(() => {
    if (!visible) {
      form.resetFields();
    }
  }, [visible]);
  useEffect(() => {
    const selectUnit = appState.unitId;
    if (selectUnit) {
      fetchFondsListByUnitId(selectUnit).then((res) => {
        const _fondList: IFond[] = res.data;
        console.log('_fondList', _fondList, baseInfo);
        setFondsList(_fondList);
        form.setFieldsValue({ fondId: _fondList[0]?.id });
      });
    }
  }, [appState.unitId]);

  const fondId = Form.useWatch('fondId', form);
  // 切换全宗自动加载档案类型
  useEffect(() => {
    if (fondId) {
      fetchATListByFondId(fondId).then((res) => {
        const _atList: IArchiveType[] = res.data;
        console.log('atList', _atList);
        setATList(_atList);
        form.setFieldsValue({ atType: _atList[0]?.id });
      });
    }
  }, [fondId]);
  const atId = Form.useWatch('atType', form);

  useEffect(() => {
    console.log('fondIdfondIdfondId', atId);

    if (atId) {
      setAtItem(selectItemByKey(atId, ATList));
      selectMappingList({
        calssification: 2,
        sourceArchiveTypeId: baseInfo.id,
        targetArchiveTypeId: atId,
        type: 1
      }).then((res) => {
        const { data } = res;
        setMappingList(data);
      });
    }
  }, [atId]);
  useEffect(() => {
    console.log('atItematItem', atItem);
    if (JSON.stringify(atItem) !== '{}' && atItem.levelList.length > 2) {
      const levelList = atItem.levelList[0];
      const coordinate = {
        atCode: levelList.atCode,
        atType: levelList.atType,
        level: levelList.level
      };
      const commonParams = {
        dbName: 'zhengbian'
      };
      fetchArchivesByRule({ commonParams, coordinate, fieldName: '', fieldValueList: [] }).then(
        (res) => {
          const { data } = res;
          setFileList(data);
          console.log('ddddddd', data);
        }
      );
    }
  }, [atItem]);
  const onFinish = (val: any) => {
    const transferArchiveSourceDTO = {
      coordinate: {
        atCode: baseInfo.atCode,
        atType: baseInfo.atType,
        level: baseInfo.atLevel
      },
      dbName: baseInfo.dbName,
      movingEntryInfo: { entryIdList: selectItems }
    };
    const transferArchiveTargetDTO = {
      coordinate: {
        atCode: atItem.atCode,
        atType: atItem.atType,
        level: atItem.atLevel
      },
      dbName: 'zhengbian',
      entryId: val.file
    };
    transferArchive({
      transferArchiveSourceDTO,
      transferArchiveTargetDTO,
      mapId: val.mapping
    });
    console.log('vvvvvvval', {
      transferArchiveSourceDTO,
      transferArchiveTargetDTO,
      mapId: val.mapping
    });
  };
  const onCancel = () => {
    onClose();
  };
  return (
    <>
      <Modal
        visible={visible}
        title="转档案"
        onCancel={onCancel}
        footer={[
          <Button onClick={onCancel} key="close">
            取消
          </Button>,
          <Button onClick={() => form.submit()} key="submit" type="primary">
            确认
          </Button>
        ]}
      >
        <Space direction="vertical" style={{ width: '100%' }}>
          <div>您已选择{selectItems.length}个条目进行归档</div>
          <Form
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
            labelAlign="left"
            form={form}
            onFinish={onFinish}
          >
            <Form.Item label="归档位置" required>
              <Radio defaultChecked={true}>导入【整编库】</Radio>
            </Form.Item>
            <Form.Item label="全宗" rules={[{ required: true }]} name="fondId">
              <Select
                placeholder="=请选择全宗="
                fieldNames={{ label: 'fondName', value: 'id' }}
                options={fondsList}
                // defaultActiveFirstOption
              ></Select>
            </Form.Item>
            <Form.Item label="档案类型" rules={[{ required: true }]} name="atType">
              <Select
                placeholder="=请选择档案类型="
                fieldNames={{ label: 'atName', value: 'id' }}
                options={ATList}
                // defaultActiveFirstOption
              ></Select>
            </Form.Item>
            {useMemo(
              () =>
                JSON.stringify(atItem) !== '{}' &&
                atItem.levelList.length > 2 && (
                  <Form.Item label="选择案卷" rules={[{ required: true }]} name="file">
                    <Select
                      placeholder="=请选择案卷="
                      options={fileList}
                      fieldNames={{ label: 'title', value: 'id' }}
                      filterOption={(input, option) =>
                        (option?.title ?? '').toLowerCase().includes(input.toLowerCase())
                      }
                      showSearch
                    ></Select>
                  </Form.Item>
                ),
              [atItem, fileList]
            )}

            <Form.Item label="映射模板" rules={[{ required: true }]} name="mapping">
              <Select
                placeholder="=请选择映射模板="
                options={mappingList}
                fieldNames={{ label: 'name', value: 'id' }}
              ></Select>
            </Form.Item>
          </Form>
        </Space>
      </Modal>
    </>
  );
};
export default memo(observer(TransferFileModal));
